<template>
  <div id="shopStatMonthlyPage">
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />
    <a-spin :spinning="loadingFilter">
      <TableFilter
        :config="filterConfig"
        @search="handleSearch"
        v-if="filterConfig"
      />
      <a-alert
        message="篩選欄"
        description="條件配置選項數據加載中"
        v-else
      ></a-alert>
    </a-spin>
    <!-- 工具欄 -->
    <a-space>
      <a-dropdown>
        <a-button type="primary" :loading="exportLoading">
          <template #icon>
            <ExportOutlined />
          </template>
          導出
        </a-button>
        <template #overlay>
          <a-menu @click="handleExport">
            <a-menu-item key="filteredData"> 按篩選導出 </a-menu-item>
            <a-menu-item key="allData"> 全部導出 </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
    </a-space>
    <div class="data-box">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'shop'"
            >{{ record.shop?.name }}({{ record.shopId }})</template
          >
          <template v-if="column.dataIndex === 'region'">{{
            record.shop?.region
          }}</template>
          <template v-if="column.dataIndex === 'totalAmount'">
            $ {{ Number(record.totalAmount).toLocaleString() }}
          </template>
          <template v-if="column.dataIndex === 'totalCommission'">
            $ {{ Number(record.totalCommission).toLocaleString() }}
          </template>
          <template v-if="column.dataIndex === 'isArchived'">
            <a-tag
              :bordered="false"
              color="success"
              v-if="record.isArchived == true"
              >已歸檔</a-tag
            >
            <a-tag :bordered="false" color="processing" v-else>未歸檔</a-tag>
          </template>
          <template v-if="column.dataIndex === 'updatedAt'">
            {{ $formatDate(record.updatedAt) }}
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { message } from "ant-design-vue";
import { ExportOutlined } from "@ant-design/icons-vue";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";
import TableFilter from "@/components/TableFilter.vue";
import {
  tableColumns,
  filterFields,
  getProcessFilterFields,
} from "@/models/shopStatMonthly";
import { createPagination } from "@/utils/pagination";
import { shopStatMonthlyApi } from "@/api";
import { useRouter, useRoute } from "vue-router";
import { watchRouteQuery } from "@/utils/routeQueryWatcherUtil";
import { useAuthUserStore } from "@/store/authUserStore";

const breadcrumbItems = [{ url: "", name: "店鋪統計" }];
const columns = tableColumns;
const filterConfig = ref<any>(null);
const router = useRouter();
const route = useRoute();

const loadingFilter = ref(true);
onMounted(async () => {
  try {
    const config = await getProcessFilterFields();
    filterConfig.value = reactive(config);
  } catch (error) {
    console.error("加載篩選配置失敗:", error);
  } finally {
    loadingFilter.value = false;
  }
});

const pagination = createPagination();

const tableData = ref([]);

const userInfo = useAuthUserStore().userInfo;

const loading = ref(false);
const fetchData = async (params?: any) => {
  try {
    loading.value = true;
    const {
      data: { list, page, limit, total },
    } = await shopStatMonthlyApi.getShopStatMonthlyList(params);
    tableData.value = list || [];
    pagination.updatePagination(page, limit, total);
  } catch (error) {
    console.error("獲取佣金列表失敗", error);
  } finally {
    loading.value = false;
  }
};

// 監聽路由變化
watchRouteQuery(fetchData);

const handleSearch = (params: any) => {
  router.push({ query: params });
};

// 導出
const exportLoading = ref(false);
const handleExport = async ({ key }: { key: string }) => {
  let params: any = {};
  if (key === "filteredData") {
    params = route.query;
  }
  exportLoading.value = true;
  try {
    await shopStatMonthlyApi.exportShopStatMonthlyList(params);
  } catch (error) {
    message.error("導出數據失敗");
  } finally {
    exportLoading.value = false;
  }
};
</script>

<style scoped></style>
